/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

import com.bayu.services.dao.TRejectionMouldDao;
import com.bayu.services.entity.TRejectionMould;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author submonkey
 */
@Controller
@RequestMapping("/mould-update.htm")
public class MouldUpdate {

    private TRejectionMouldDao dao;

    @Autowired
    public void setDao(TRejectionMouldDao dao) {
        this.dao = dao;
    }

    @RequestMapping(method=RequestMethod.GET)
    public void displayForm(ModelMap map, String id) {
        List list = this.dao.getById(Long.parseLong(id));
        map.addAttribute("data", list);
    }

    @RequestMapping(method=RequestMethod.POST)
    public String processForm(@ModelAttribute("TRejectionMould") TRejectionMould rejectionMould,
            BindingResult result, ModelMap map, String date, HttpServletRequest request) {
        DateFormat format = new SimpleDateFormat("yy-MM-dd");
        Date tanggal;

        if (result.hasFieldErrors("date")) {
            try {
                tanggal = format.parse(date);
                rejectionMould.setDate(tanggal);
            } catch (Exception e) {
            }
        }

        String id = request.getParameter("id");

        if (id != null) {
            rejectionMould.setId(Long.parseLong(id));
            this.dao.update(rejectionMould);
            return "redirect:view-mould-data.htm?msg=Data has been updated";
        } else {
            return "redirect:mould-update.htm";
        }
    }

}
